/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.api.wlhy.driver;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.EntityDict;
import org.jeecg.common.constant.AIConstant;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ExamineStatusEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.model.SysLoginModel;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.third.aipocr.AipFaceService;
import org.jeecg.modules.third.face.FaceHelperService;
import org.jeecg.modules.third.face.resp.DataResp;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverReq;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static org.jeecg.modules.api.wlhy.vehicle.ApiVehicleController.isInDate;

/**
 * 在这里编写类的功能描述
 *
 * @author duanlikao
 * @created 2020/12/4
 */
@Api(tags = "APP司机管理")
@RestController
@RequestMapping("/api/wlhy/driver")
@Slf4j
public class ApiDriverController extends JeecgController<HyDriver, IHyDriverService> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiDriverController.class);
    /**
     * 人脸识别缓存key
     */
    private static final String FACEDETECT_UID_CACHE_KEY = "faceDetect_uid_";

    @Autowired
    private IHyDriverBankService hyDriverBankService;

    @Autowired
    private IHyDriverService hyDriverService;

    @Resource
    private BaseCommonService baseCommonService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private FaceHelperService faceHelperService;

    @Resource
    private IHySettingService settingService;

    @Autowired
    private AipFaceService aipFaceService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserUtil userUtil;



    /**
     * 测试位置信息是否调用
     *
     * @return
     */
    @ApiOperation(value = "APP测试位置信息是否调用", notes = "APP测试位置信息是否调用")
    @PostMapping(value = "/testLocationLog")
    public void testLocationLog() {
        log.info("/api/wlhy/driver/testLocationLog APP测试位置信息是否调用");
    }

    /**
     * 添加
     *
     * @param hyDriver
     * @return
     */
    @AutoLog(value = "APP司机管理-保存")
    @ApiOperation(value = "APP司机管理-保存", notes = "APP司机管理-保存")
    @PostMapping(value = "/save")
    @CacheEvict(value = CacheConstant.SYS_DICT_TABLE_CACHE ,key = "'SimpleKey [hy_driver,driver_name,id,' + #hyDriver.id + ']'")
    public Result<?> save(@RequestBody @Valid HyDriverReq hyDriver) {

        SysUser user = userUtil.getUser();
        hyDriverService.checkValidUser(user);

        Result<JSONObject> result;

        hyDriver.setUserId(user.getId());

        if (StringUtils.isEmpty(hyDriver.getTelephone())) {
            throw new JeecgBootException("手机号不允许为空");
        }

        String feeCalc = HyCfgUtil.getCfgValue2("driver_upload_simplification");
        log.info("简化版参数打印： {}", feeCalc);
        if(StrUtil.isEmpty(feeCalc) || !feeCalc.equals("1")) {
            this.doCheckDriver(hyDriver);
            result = hyDriverService.saveHyDriver(HyDriverReqTOHyDriver(hyDriver));
            if (!result.isSuccess()) {
                return result;
            }
            //添加日志
            baseCommonService.addLog("司机用户: " + hyDriver.getDriverName() + ",司机信息保存成功！",
                    CommonConstant.LOG_TYPE_1, null);
            return result;
        }
        result = hyDriverService.saveHyDriver(HyDriverReqTOHyDriver(hyDriver));
        if (!result.isSuccess()) {
            return result;
        }
        //添加日志
        baseCommonService.addLog("司机用户: " + hyDriver.getDriverName() + ",司机信息保存成功！",
                CommonConstant.LOG_TYPE_1, null);
        return result;

    }

    /**
     * 司机注册
     *
     * @param sysLoginModel
     * @return
     */
    @AutoLog(value = "APP司机管理-司机注册")
    @ApiOperation(value = "APP司机管理-司机注册", notes = "APP司机管理-司机注册")
    @PostMapping(value = "/register")
    @EntityDict
    public Result<?> register(@RequestBody SysLoginModel sysLoginModel, HttpServletResponse response) {
        Result<JSONObject> result = new Result<JSONObject>();
        String phone = sysLoginModel.getPhone();
        String smscode = sysLoginModel.getSmscode();
        Object code = redisUtil.get(phone);
        SysUser sysUser1 = sysUserService.getUserByPhone(phone);
        if (sysUser1 != null) {
            result.setMessage("该手机号已注册");
            result.setSuccess(false);
            return result;
        }
        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }
        result = sysUserService.registerDriver(sysLoginModel, response);

        //添加日志
        baseCommonService.addLog("司机用户: " + phone + ",注册成功！",
                CommonConstant.LOG_TYPE_1, null);
        return result;
    }

    //设置登陆次数超过5次，锁定10分钟
    private boolean isDidableLogin(String username) {
        String loginkey = "loginfail:" + username;
        //检查是否超过5次
        if (redisUtil.hasKey(loginkey)) {
            int loginNum = (int) redisUtil.get(loginkey);
            if (loginNum >= 5) {
                return true;
            }
        }
        return false;
    }

    //设置登陆次数超过5次，锁定10分钟
    private void addLoginNum(String username) {
        String loginkey = "loginfail:" + username;
        if (!redisUtil.hasKey(loginkey)) {
            redisUtil.set(loginkey, 1, 10 * 60);
        } else {
            int loginNum = (int) redisUtil.get(loginkey);
            loginNum = loginNum + 1;
            redisUtil.set(loginkey, loginNum, 10 * 60);
        }
    }

    /**
     * 手机号登录接口
     *
     * @param jsonObject
     * @return
     */
    @ApiOperation("APP司机管理-第三方登陆")
    @PostMapping("/thirdPlatsLogin")
    @EntityDict
    public Result<?> thirdPlatsLogin(@RequestBody JSONObject jsonObject) {
        Result<JSONObject> result;
        String phone = jsonObject.getString("phone");
        if (StringUtils.isBlank(phone)) {
            return Result.error("手机号不能为空");
        }
        if (isDidableLogin(phone)) {
            return Result.error("连续登陆失败5次，账户锁定10分钟！");
        }
        String openid = jsonObject.getString("openid");
        if (StringUtils.isBlank(openid)) {
            return Result.error("openid不能为空");
        }
//        Object code = redisUtil.get(phone);
//        if (!openid.equals(code)) {
//            addLoginNum(phone);
//            return Result.error("手机验证码错误");
//        }
        //校验用户有效性
        SysUser sysUser = sysUserService.getUserByPhone(phone);
        result = sysUserService.checkUserIsEffective(sysUser);
        if (!result.isSuccess()) {
            return result;
        }

        if (!"4".equals(sysUser.getUType())) {
            addLoginNum(phone);
            return Result.error("不是司机账号");
        }

        hyDriverService.checkValidUser(sysUser);
        //用户信息
        sysUserService.appUserInfo(sysUser, result);
        if (StringUtils.isNotBlank(openid)) {
            sysUser.setThirdId(openid);
            sysUser.setThirdType("微信登陆");
            sysUserService.updateById(sysUser);
        }
        //添加日志
        baseCommonService.addLog("司机用户: " + sysUser.getUsername() + ",微信登陆成功！",
                CommonConstant.LOG_TYPE_1, null);

        return result;
    }

    /**
     * 手机号登录接口
     *
     * @param jsonObject
     * @return
     */
    @ApiOperation("APP司机管理-司机手机登陆")
    @PostMapping("/phoneLogin")
    @EntityDict
    public Result<?> phoneLogin(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        Result<JSONObject> result;
        String phone = jsonObject.getString("phone");
        if (StringUtils.isEmpty(phone)) {
            return Result.error("手机号不能为空");
        }
        if (isDidableLogin(phone)) {
            return Result.error("连续登陆失败5次，账户锁定10分钟！");
        }
        String smscode = jsonObject.getString("smscode");
        if (StringUtils.isEmpty(smscode)) {
            return Result.error("手机验证码不能为空");
        }

        Object code = redisUtil.get(phone);
        if (!smscode.equals(code)) {
            addLoginNum(phone);
            return Result.error("手机验证码错误");
        }


        String clientId = jsonObject.containsKey("clientId") ? jsonObject.getString("clientId") : StringUtils.EMPTY;
        //校验用户有效性
        SysUser sysUser = sysUserService.getUserByPhone(phone);
        result = sysUserService.checkUserIsEffective(sysUser);
        if (!result.isSuccess()) {
            addLoginNum(phone);
            return result;
        }

        if (!"4".equals(sysUser.getUType())) {
            addLoginNum(phone);
            return Result.error("不是司机账号");
        }

        hyDriverService.checkValidUser(sysUser);
        //用户信息
        sysUserService.appUserInfo(sysUser, result);
        if (StringUtils.isNotEmpty(clientId)) {
            sysUser.setClientId(clientId);
            sysUserService.updateById(sysUser);
        }
        //保存cookie
        setUserCookie(sysUser.getUsername(), response);
        //添加日志
        baseCommonService.addLog("司机用户: " + sysUser.getUsername() + ",登录成功！",
                CommonConstant.LOG_TYPE_1, null);

        return result;
    }

    /**
     * 司机登录
     *
     * @param sysLoginModel
     * @return
     */
    @AutoLog(value = "APP司机管理-司机账号登陆")
    @ApiOperation(value = "APP司机管理-司机账号登陆", notes = "APP司机管理-司机账号登陆")
    @PostMapping(value = "/login")
    @EntityDict
    public Result<?> login(@RequestBody SysLoginModel sysLoginModel, HttpServletResponse response) {
        Result<JSONObject> result = new Result<JSONObject>();
        String phone = sysLoginModel.getUsername();
        if (StringUtils.isEmpty(phone)) {
            result.error500("用户名不能为空");
            return result;
        }

        if (isDidableLogin(phone)) {
            result.error500("连续登陆失败5次，账户锁定10分钟！");
            return result;
        }

        String password = sysLoginModel.getPassword();
        if (StringUtils.isEmpty(password)) {
            result.error500("密码不能为空");
            return result;
        }

        SysUser sysUser = sysUserService.getUserByPhone(phone);
        result = sysUserService.checkUserIsEffective(sysUser);
        if (!result.isSuccess()) {
            addLoginNum(phone);
            return result;
        }

        if (!"4".equals(sysUser.getUType())) {
            addLoginNum(phone);
            return Result.error("不是司机账号");
        }

        String username = sysUser.getUsername();
        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
        String syspassword = sysUser.getPassword();
        if (!syspassword.equals(userpassword)) {
            addLoginNum(phone);
            return Result.error("用户名或密码错误");
        }

        hyDriverService.checkValidUser(sysUser);
        //用户登录信息
        sysUserService.appUserInfo(sysUser, result);
        if (StringUtils.isNotEmpty(sysLoginModel.getClientId())) {
            sysUser.setClientId(sysLoginModel.getClientId());
            sysUserService.updateById(sysUser);
        }
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUser, loginUser);

        //保存cookie
        setUserCookie(sysUser.getUsername(), response);
        baseCommonService.addLog("司机: " + phone + ",登录成功！",
                CommonConstant.LOG_TYPE_1, null, loginUser);

        return result;
    }


    private void setUserCookie(String username, HttpServletResponse response) {
        Cookie cookie= new Cookie(CommonConstant.X_PC_COOKIE, MD5Util.MD5Encode(username, "utf-8"));
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30);
        cookie.setHttpOnly(true);
        ((HttpServletResponse)response).addCookie(cookie);
        log.info("APP司机登录设置cookie - CMAP_SECKEY - {}", cookie.getValue());

        return;
    }


    @AutoLog(value = "APP司机管理-修改手机号")
    @ApiOperation(value="APP司机管理-修改手机号", notes="APP司机管理-修改手机号")
    @PutMapping(value = "/modifyphone")
    public Result<?> modifyphone(@RequestBody JSONObject jsonObject) {
        HyDriver driver = userUtil.getDriver();

        String newPhone = jsonObject.getString("newPhone");
        String smscode  = jsonObject.getString("smscode");

        if(StringUtils.isBlank(newPhone)){
           return Result.error("新手机号不能为空!");
        }
        if (newPhone.length() != 11) {
            throw new JeecgBootException("手机号应为11位数。");
        }
        if (!newPhone.matches(CommonConstant.REGEX_MOBILE)) {
            throw new JeecgBootException("手机号格式错误！");
        }

        if(StringUtils.equals(driver.getTelephone(),newPhone)){
            return Result.error("新手机号不能和原手机号相同!");
        }

        if (StringUtils.isEmpty(smscode)) {
            return Result.error("新手机号验证码不能为空");
        }

        String code = redisUtil.hasKey(newPhone) ? String.valueOf(redisUtil.get(newPhone)) : StringUtils.EMPTY;
        if (!smscode.equals(code)) {
            return Result.error("手机验证码错误");
        }

        return hyDriverService.modifyPhone(driver, newPhone);
    }




    @ApiOperation(value = "APP司机管理-获取当前登陆司机信息", notes = "APP司机管理-获取当前登陆司机信息")
    @GetMapping(value = "/getDriverInfo")
    @EntityDict
    public Result<?> getDriverInfo() {
        HyDriver driver = userUtil.getDriver();
        //driverTOHyDriverReq(driver)
//        System.out.println(driver);
//        System.out.println(driver.getDriverAutograph());
        return Result.OK(driver);
    }

    @ApiOperation(value = "APP司机管理-获取当前登陆司机用户信息", notes = "APP司机管理-获取当前登陆司机用户信息")
    @GetMapping(value = "/getDriverUserInfo")
    @EntityDict
    public Result<?> getDriverUserInfo() {
        return hyDriverService.getRefreshDriverUserInfo();
    }


    @ApiOperation(value = "APP司机管理-获取验证码", notes = "APP司机管理-获取验证码")
    @GetMapping(value = "/getSmsCode")
    public Result<?> getSmsCode(@RequestParam(name = "phone") String phone) {
//        if (StringUtils.isNotEmpty(phone) && phone.length() != 11) {
//            throw new JeecgBootException("手机号应为11位数。");
//        }
//        if (StringUtils.isNotEmpty(phone) && !phone.matches(CommonConstant.REGEX_MOBILE)) {
//            throw new JeecgBootException("手机号格式错误！");
//        }
//        String code = redisUtil.hasKey(phone) ? String.valueOf(redisUtil.get(phone)) : StringUtils.EMPTY;
//        return StringUtils.isNotEmpty(code) ? Result.OK(code) : Result.error(phone + " 该手机号验证码没有发送成功！");
        return Result.OK();
    }

    @AutoLog(value = "APP司机管理-银行卡保存")
    @ApiOperation(value = "APP司机管理-银行卡保存", notes = "APP司机管理-银行卡保存")
    @PostMapping(value = "/driverbank/save")
    public Result<?> hyDriverBankSave(@RequestBody HyDriverBank hyDriverBank) {
        if(StringUtils.isEmpty(hyDriverBank.getBankNum())){
            return Result.error("银行卡号不能为空");
        }

        HyDriver hyDriver = userUtil.getDriver();


        hyDriverBank.setBankNum(hyDriverBank.getBankNum().replaceAll(" ","").trim());

        HyDriverBank driverBankDb = hyDriverBankService.getDriverBankInfo(hyDriver.getId(), hyDriverBank.getBankNum());

       /* if(HyCfgUtil.isUsed2("driver_binding_card")){
            if(!driverBankDb.getBankName().equals(hyDriver.getDriverName())){
                return Result.error("请绑定本人银行卡");
            }
        }*/
        //Added at 2023-09-09 for 判断必须绑定本人银行卡
        if ("1".equals(settingService.getSettingValueByTag2("self_bankcard"))) {
           /* if (!hyDriver.getDriverName().equals(hyDriverBank.getBankName())) {
                return Result.error("当前系统已限定绑定本人银行卡，请联系平台管理员");
            }*/
            if ("0".equals(hyDriverBank.getSt()) || StringUtils.isNotEmpty(hyDriverBank.getBankName())) {
                return Result.error("当前系统已限定绑定本人银行卡，请联系平台管理员");
            }
        }
        if(driverBankDb != null && "1".equals(driverBankDb.getDelFlag())){
            //司机解绑后重新绑定同一张卡
            driverBankDb.setDelFlag("0");
            driverBankDb.setIzUsed("1");
            // Added start at 2025-03-01 for 解绑后再绑定同一个银行卡号时，如果bankname和idcard变了也要更新
            if (StrUtil.isNotEmpty(hyDriverBank.getBankName())) {
                driverBankDb.setBankName(hyDriverBank.getBankName());
            }
            driverBankDb.setIdcard(hyDriverBank.getIdcard());
            driverBankDb.setBankType(hyDriverBank.getBankType());
            if (StrUtil.isNotEmpty(hyDriverBank.getBankPhone())) {
                driverBankDb.setBankPhone(hyDriverBank.getBankPhone());
            }
            // Added end at 2025-03-01 for 解绑后再绑定同一个银行卡号时，如果bankname和idcard变了也要更新
            hyDriverBankService.updateById(driverBankDb);
            return Result.OK();
        }
        if (StringUtils.isNotEmpty(hyDriverBank.getId())) {
            HyDriverBank driverBank = hyDriverBankService.getById(hyDriverBank.getId());
            if (driverBank == null) {
                return Result.error("数据不存在");
            }
            if (!StringUtils.equals(hyDriver.getId(), driverBank.getDriverId())) {
                return Result.error("数据错误");
            }
            if (StringUtils.equals(driverBank.getBankNum(), hyDriverBank.getBankNum()) &&
                    StringUtils.equals(driverBank.getBankName(), hyDriverBank.getBankName()) &&
                    StringUtils.equals(driverBank.getBankType(), hyDriverBank.getBankType())) {
                return Result.OK("修改成功");
            }
            return hyDriverBankService.updateDriverBank(hyDriverBank);
        } else {
            if("1".equals(hyDriverBank.getSt())){
                hyDriverBank.setBankName(hyDriver.getDriverName());
                hyDriverBank.setIdcard(hyDriver.getIdcard());
            }
            hyDriverBank.setUserId(hyDriver.getUserId());
            hyDriverBank.setDriverId(hyDriver.getId());
            hyDriverBank.setIzUsed("1");
            return hyDriverBankService.addDriverBank(hyDriverBank);
        }
    }

    @AutoLog(value = "APP司机管理-银行卡设置默认银行卡")
    @PostMapping(value = "/setDefaultDriverBank")
    public Result<?> setDefault(@RequestBody JSONObject jo) {
        String id = jo.getString("id");
        if (StringUtils.isEmpty(id)) {
            return Result.error("id不能为空");
        }
        HyDriverBank driverBank = hyDriverBankService.getById(id);
        if (driverBank == null) {
            return Result.error("数据不存在");
        }
        HyDriver hyDriver = userUtil.getDriver();
        if (!StringUtils.equals(hyDriver.getId(), driverBank.getDriverId())) {
            return Result.error("数据错误");
        }
        return hyDriverBankService.setDefault(driverBank);
    }

    @ApiOperation(value = "APP司机管理-银行卡列表", notes = "APP司机管理-银行卡列表")
    @GetMapping(value = "/driverbank/list")
    public Result<?> queryPageList(HyDriverBank hyDriverBank,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize,
                                   HttpServletRequest req) {
        HyDriver driver = userUtil.getDriver();
        QueryWrapper<HyDriverBank> queryWrapper = QueryGenerator.initQueryWrapper(hyDriverBank, req.getParameterMap());
        queryWrapper.eq("driver_id", driver.getId());
        queryWrapper.eq("iz_used", "1");
        Page<HyDriverBank> page = new Page<HyDriverBank>(pageNo, pageSize);
        IPage<HyDriverBank> pageList = hyDriverBankService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "APP司机管理-银行卡解绑")
    @ApiOperation(value = "APP司机管理-银行卡解绑", notes = "APP司机管理-银行卡解绑")
    @PostMapping(value = "/driverbank/unbundling")
    public Result<?> unBundLing(@RequestParam(name = "id") String id) {
        HyDriver driver = userUtil.getDriver();
        HyDriverBank driverBank = hyDriverBankService.getById(id);
        if (driverBank == null) {
            return Result.error("解绑失败");
        }
        if (!StringUtils.equals(driver.getId(), driverBank.getDriverId())) {
            return Result.error("数据错误");
        }
        driverBank.setIzUsed("0");
        driverBank.setDelFlag("1");
        hyDriverBankService.updateById(driverBank);
//        hyDriverBankService.removeById(id);
        //添加日志
        baseCommonService.addLog("司机用户: " + driver.getDriverName() + ",司机银行卡解绑成功！",
                CommonConstant.LOG_TYPE_1, null);
        return Result.OK("解绑成功");
    }

    @ApiOperation(value = "APP司机管理-人脸识别", notes = "APP司机管理-人脸识别")
    @PostMapping("/face/faceDetect")
    @ResponseBody
    public Result<?> faceDetect(@RequestBody String imgBase64, HttpServletRequest req) throws IOException {

        HyDriver driver = userUtil.getDriver();
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
//        MultipartFile file = multipartRequest.getFile("file");
//        String imgBase64 = Base64Util.encode(file.getBytes());

        DataResp dataResp = faceHelperService.faceDetect(imgBase64);
        if (dataResp.getCode() == CommonConstant.SC_OK_200) {
            redisUtil.set(FACEDETECT_UID_CACHE_KEY + driver.getUserId(), dataResp.getData().toString());
            redisUtil.expire(FACEDETECT_UID_CACHE_KEY + driver.getUserId(), 60 * 10);
        }
        return getResult(dataResp);

    }

    @ApiOperation(value = "APP司机管理-人脸对比", notes = "APP司机管理-人脸对比")
    @PostMapping("/face/faceCompare")
    @ResponseBody
    public Result<?> faceCompare(@RequestBody String imgBase64) {
        HyDriver driver = userUtil.getDriver();
        String imgBase64No1 = redisUtil.get(FACEDETECT_UID_CACHE_KEY + driver.getUserId()).toString();
        if (StringUtils.isEmpty(imgBase64No1)) {
            throw new JeecgBootException("你的人脸识别信息不存在");
        }
        DataResp dataResp = faceHelperService.faceCompare(imgBase64No1, imgBase64);
        return getResult(dataResp);
    }


    @ApiOperation(value = "APP司机管理-活体检测", notes = "APP司机管理-活体检测")
    @PostMapping("/face/aliveCheck")
    @ResponseBody
    public Result<?> aliveCheck(@RequestBody String imgBase64, String checkType, HttpServletRequest req) {
        HyDriver driver = userUtil.getDriver();
        DataResp dataResp = faceHelperService.aliveCheck(imgBase64, checkType, driver.getUserId());
        return getResult(dataResp);
    }


    @ApiOperation(value = "APP司机管理-百度人脸对比", notes = "APP司机管理-百度人脸对比")
    @PostMapping("/face/matchFace")
    @ResponseBody
    public Result<?> matchFace(@RequestBody JSONObject object) {

        String imageBase64No1 = object.get("imageBase64No1") != null ? object.get("imageBase64No1").toString() : StringUtils.EMPTY;
        String imageBase64No2 = object.get("imageBase64No2") != null ? object.get("imageBase64No2").toString() : StringUtils.EMPTY;
        if (StringUtils.isEmpty(imageBase64No1) || StringUtils.isEmpty(imageBase64No2)) {
            return Result.error("你的人脸对比参数不完整!");
        }
        //检查是否开启身份证验证
        String settingValue = settingService.getSettingValueByTag2("ID_card_check");
        if (settingValue.equals("1")) {
            String resourcesString = aipFaceService.matchFace(imageBase64No1, imageBase64No2);
            if (StringUtils.isNotEmpty(resourcesString)) {
                JSONObject jsonObject = JSONObject.parseObject(resourcesString);
                String result = jsonObject.get("result") != null ? jsonObject.get("result").toString() : null;
                JSONObject resultJsonObject = StringUtils.isNotEmpty(result) ?
                        JSONObject.parseObject(result) : new JSONObject();
                if (resultJsonObject.get("score") != null) {
                    String scoreString = resultJsonObject.get("score").toString();
                    Integer score = Double.valueOf(scoreString).intValue();
                    return score > AIConstant.AI_FACE_COMPARE_SCORE ?
                            Result.OK() :
                            Result.error("人脸对比失败,不是同一个人!");
                }
                if (resultJsonObject.get("error_code") != null) {
                    return Result.error(resultJsonObject.get("error_msg").toString());
                }
            }
        }
        return Result.OK();

    }

    private Result<?> getResult(DataResp dataResp) {
        if (dataResp == null) {
            return null;
        }
        if (dataResp.getCode() == CommonConstant.SC_OK_200) {
            return Result.OK((JSONObject) dataResp.getData());
        }
        return Result.error(dataResp.getCode(), dataResp.getMessage());

    }


    @ApiOperation(value = "APP司机管理-银行卡号检查", notes = "APP司机管理-银行卡号检查")
    @PostMapping("/driverbank/checkbanknum")
    @ResponseBody
    public Result<?> checkBankNum(@RequestParam(name = "bankNum") String bankNum, HttpServletRequest req) {
        HyDriver driver = userUtil.getDriver();

        if (StringUtils.isNotEmpty(bankNum) &&
                !CheckBankCardIUtil.checkBankCard(bankNum)) {
            return Result.error("请输入有效银行卡号！");
        }
        JSONObject obj = new JSONObject();
        obj.put("bankNum", bankNum);
        String res = CheckBankCardIUtil.getCardDetail(bankNum);
        if (StringUtils.isNotEmpty(res)) {
            JSONObject jsonObject = JSONObject.parseObject(res);
            if (jsonObject.get("stat").equals("ok")) {
                String key = jsonObject.get("key").toString();
                if (!((Boolean) jsonObject.get("validated"))) {
                    return Result.error("请输入有效银行卡号！");
                }
                obj.put("bankNum", key);
            }
        }
        Map<String, String> bankMaps = new HashMap<>();
        bankMaps.put("中国银行", "BKCH");
        bankMaps.put("工商银行", "ICBK");
        bankMaps.put("农业银行", "ABOC");
        bankMaps.put("建设银行", "PCBC");

        BankInfoBean bankinfobean = new BankInfoBean(bankNum);
        if (bankMaps.containsKey(bankinfobean.getBankName())) {
            String bankType = bankMaps.get(bankinfobean.getBankName());
            obj.put("bankType", bankType);

        }

        return Result.ok(obj);

    }

    public static HyDriverReq driverTOHyDriverReq(HyDriver item) {
        if (item == null) {
            return null;
        }
        HyDriverReq result = new HyDriverReq();
        result.setId(item.getId());
        result.setUserId(item.getUserId());
        result.setDriverName(item.getDriverName());
        result.setIdcard(item.getIdcard());
        result.setIdcardValidFrom(
                item.getIdcardValidFrom() != null ?
                        DateUtils.date2Str(item.getIdcardValidFrom(),DateUtils.date_sdf.get())
                        :""
        );
       String idcardExpiredDate =   item.getIdcardExpiredDate() != null ?
                DateUtils.date2Str(item.getIdcardExpiredDate(),DateUtils.date_sdf.get())
                :"" ;

        result.setIdcardExpiredDate(
             StringUtils.isNotBlank(idcardExpiredDate)  &&   idcardExpiredDate.contains("9999") ?  "长期" : idcardExpiredDate
        );
        result.setIdcardImg(item.getIdcardImg());
        result.setIdcardImgBack(item.getIdcardImgBack());
        result.setSex(item.getSex());
        result.setTelephone(item.getTelephone());
        result.setNativePlace(item.getNativePlace());
        result.setNation(item.getNation());
        result.setBirthday(
                item.getBirthday() != null ?
                        DateUtils.date2Str(item.getBirthday(),DateUtils.date_sdf.get())
                        :"");

        result.setAddress(item.getAddress());
        result.setCarrierId(item.getCarrierId());
        result.setDrivingLicense(item.getDrivingLicense());
        result.setDriverImg(item.getDriverImg());
        result.setDriverImg2(item.getDriverImg2());
        result.setVehicleClass(item.getVehicleClass());
        result.setIssuingOrganizations(item.getIssuingOrganizations());
        result.setIssueStartDate(
                item.getIssueStartDate() != null ?
                        DateUtils.date2Str(item.getIssueStartDate(),DateUtils.date_sdf.get())
                        :""
           );
        result.setValidPeriodFrom(
                item.getValidPeriodFrom() != null ?
                        DateUtils.date2Str(item.getValidPeriodFrom(),DateUtils.date_sdf.get())
                        :""
               );
        String validPeriodTo =   item.getValidPeriodTo() != null ?
                DateUtils.date2Str(item.getValidPeriodTo(),DateUtils.date_sdf.get())
                :"" ;

        result.setValidPeriodTo(
                StringUtils.isNotBlank(validPeriodTo)  &&   validPeriodTo.contains("9999") ?  "长期" : validPeriodTo
        );
        result.setWeightType(item.getWeightType());
        result.setQualificationCertificate(item.getQualificationCertificate());
        result.setQualificationImg(item.getQualificationImg());
        result.setQualificationExpiredDate(
                item.getQualificationExpiredDate() != null ?
                        DateUtils.date2Str(item.getQualificationExpiredDate(),DateUtils.date_sdf.get())
                        :""
        );
        result.setIzAffiliation(item.getIzAffiliation());
        result.setAffiliationAgreement(item.getAffiliationAgreement());
        result.setCreateBy(item.getCreateBy());
        result.setAreaCode(item.getAreaCode());
        result.setExamineStatus(item.getExamineStatus());
        return result;
    }



    public static HyDriver HyDriverReqTOHyDriver(HyDriverReq hyDriverReq) {
        if (hyDriverReq == null) {
            return null;
        }
        HyDriver hyDriver = new HyDriver();
        hyDriver.setId(hyDriverReq.getId());
        hyDriver.setUserId(hyDriverReq.getUserId());
        hyDriver.setDriverName(hyDriverReq.getDriverName());
        hyDriver.setIdcard(hyDriverReq.getIdcard());

        hyDriver.setIdcardExpiredDate(
                StringUtils.isNotEmpty(hyDriverReq.getIdcardExpiredDate()) ? DateUtils.getStrToDate(hyDriverReq.getIdcardExpiredDate()) : null
        );
        Date idcardExpiredDate = StringUtils.isNotEmpty(hyDriverReq.getIdcardExpiredDate()) && hyDriverReq.getIdcardExpiredDate().contains("9999") ?
                new Date() : hyDriver.getIdcardExpiredDate();
        Date idcardValidFrom = null;
        if (idcardExpiredDate != null) {
            Calendar calend = Calendar.getInstance();
            calend.setTime(idcardExpiredDate);
            calend.add(Calendar.YEAR, -20);
            idcardValidFrom = calend.getTime();
        }
        hyDriver.setIdcardValidFrom(
                StringUtils.isNotEmpty(hyDriverReq.getIdcardValidFrom()) ?
                        DateUtils.getStrToDate(hyDriverReq.getIdcardValidFrom()) : idcardValidFrom
        );

        hyDriver.setIdcardImg(hyDriverReq.getIdcardImg());
        hyDriver.setIdcardImgBack(hyDriverReq.getIdcardImgBack());
        hyDriver.setSex(hyDriverReq.getSex());
        hyDriver.setTelephone(hyDriverReq.getTelephone());
        hyDriver.setNativePlace(hyDriverReq.getNativePlace());
        hyDriver.setNation(hyDriverReq.getNation());
        hyDriver.setBirthday(
                StringUtils.isNotEmpty(hyDriverReq.getBirthday()) ? DateUtils.getStrToDate(hyDriverReq.getBirthday()) : null
        );
        hyDriver.setAddress(hyDriverReq.getAddress());
        hyDriver.setCarrierId(hyDriverReq.getCarrierId());
        hyDriver.setDrivingLicense(hyDriverReq.getDrivingLicense());
        hyDriver.setDriverImg(hyDriverReq.getDriverImg());
        hyDriver.setDriverImg2(hyDriverReq.getDriverImg2());
        hyDriver.setVehicleClass(hyDriverReq.getVehicleClass());
        hyDriver.setIssuingOrganizations(hyDriverReq.getIssuingOrganizations());
        hyDriver.setValidPeriodFrom(
                StringUtils.isNotEmpty(hyDriverReq.getValidPeriodFrom()) ? DateUtils.getStrToDate(hyDriverReq.getValidPeriodFrom()) : null
        );
        Calendar cal = Calendar.getInstance();
        cal.setTime(hyDriver.getValidPeriodFrom());
        cal.add(Calendar.YEAR, 10);
        Date validPeriodTo = cal.getTime();
        hyDriver.setValidPeriodTo(
                 StringUtils.isNotEmpty(hyDriverReq.getValidPeriodTo())  ?  DateUtils.getStrToDate(hyDriverReq.getValidPeriodTo()) : validPeriodTo
        );
        //Added start at 2024-07-19 for 极其特殊的情况处理To和From一样，大概率是华为云识别的问题
        //如果一样了，用from的时间再加10年作为结束日期
        if (StrUtil.isNotEmpty(hyDriverReq.getValidPeriodFrom()) && hyDriverReq.getValidPeriodFrom().equals(hyDriverReq.getValidPeriodTo())) {
            hyDriver.setValidPeriodTo(validPeriodTo);
        }
        //Added end at 2024-07-19 for 极其特殊的情况处理To和From一样，大概率是华为云识别的问题

        hyDriver.setWeightType(hyDriverReq.getWeightType());
        hyDriver.setQualificationCertificate(hyDriverReq.getQualificationCertificate());
        hyDriver.setQualificationImg(hyDriverReq.getQualificationImg());
        hyDriver.setQualificationExpiredDate(
                StringUtils.isNotEmpty(hyDriverReq.getQualificationExpiredDate()) ?
                        DateUtils.getStrToDate(hyDriverReq.getQualificationExpiredDate()) : null
        );
        hyDriver.setIzAffiliation(hyDriverReq.getIzAffiliation());
        hyDriver.setAffiliationAgreement(hyDriverReq.getAffiliationAgreement());
        hyDriver.setCreateBy(hyDriverReq.getCreateBy());
        hyDriver.setAreaCode(hyDriver.getIdcard().substring(0, 6));

        hyDriver.setIssueStartDate(
                StringUtils.isNotEmpty(hyDriverReq.getIssueStartDate()) ?
                        DateUtils.getStrToDate(hyDriverReq.getIssueStartDate()) : null
        );
        hyDriver.setExamineStatus(hyDriverReq.getExamineStatus());
        return hyDriver;
    }

    /**
     * 验证驾驶证真实性
     *
     * @param hyDriver
     */
    private void doCheckDriver(HyDriverReq hyDriver) {

        if (StringUtils.isEmpty(hyDriver.getValidPeriodFrom())) {
            throw new JeecgBootException("驾驶证有效期不允许为空");
        }
        Date validPeriodFrom = DateUtils.getStrToDate(hyDriver.getValidPeriodFrom());
        if (validPeriodFrom == null) {
            throw new JeecgBootException("驾驶证有效期格式错误,请重新填写!");
        }

        /*if (validPeriodFrom.after(new Date())) {
            throw new JeecgBootException("驾驶证有效期自过去的时间,请重新填写!");
        }*/

        if (StringUtils.isEmpty(hyDriver.getValidPeriodTo())) {
            throw new JeecgBootException("驾驶证有效期至不允许为空");
        }else{
            if("长期".equals(hyDriver.getValidPeriodTo())){
                hyDriver.setValidPeriodTo("9999-12-31");
            }
            //针对昆交驾驶证有效期长期识别错误修复
            int num1 = Integer.parseInt(StringUtils.substring(hyDriver.getValidPeriodFrom(),0,4));
            String a = StringUtils.substring(hyDriver.getValidPeriodTo(),4,12);
            int num2 = Integer.parseInt(StringUtils.substring(hyDriver.getValidPeriodTo(),0,4));
            String type = hyDriver.getVehicleClass();
            if (type.contains("A")){
                if (num2-num1<10){
                    num2 = num1+10;
                    hyDriver.setValidPeriodTo(String.valueOf(num2)+a);
                }
            } else  {
                if (num2-num1<6){
                    num2 = num1+6;
                    hyDriver.setValidPeriodTo(String.valueOf(num2)+a);
                }
            }


        }
        Date validPeriodTo = DateUtils.getStrToDate(hyDriver.getValidPeriodTo());
        if (validPeriodTo == null) {
            throw new JeecgBootException("驾驶证有效期至,请重新填写!");
        }

        if (validPeriodTo.before(new Date())) {
            throw new JeecgBootException("驾驶证有效期至需要一个将来时间,请重新填写!");
        }
        //快货运字段start-------------------------------------
        //检查是否开启身份证有效期自

        if (StringUtils.isNotEmpty(hyDriver.getIdcardExpiredDate())) {
            if("长期".equals(hyDriver.getIdcardExpiredDate())){
                hyDriver.setIdcardExpiredDate("9999-12-31");
            }
        }

        if (StringUtils.isNotEmpty(hyDriver.getIdcardValidFrom())) {
            Date roadTransportExpiredDate = DateUtils.getStrToDate(hyDriver.getIdcardValidFrom());
            if (roadTransportExpiredDate == null) {
                throw new JeecgBootException("身份证有效期自时间格式错误,请重新填写!");
            }
        }


        //检查是否开启驾驶证首次签发日期

        if (StringUtils.isNotEmpty(hyDriver.getIssueStartDate())) {
            Date roadTransportExpiredDate = DateUtils.getStrToDate(hyDriver.getIssueStartDate());
            if (roadTransportExpiredDate == null) {
                throw new JeecgBootException("驾驶证首次签发日期格式错误,请重新填写!");
            }
        }

        if(!"C1".equals(hyDriver.getVehicleClass())){
            //获取从业资格证是否必填
            String qualificationCertificateUpload = settingService.getSettingValueByTag("qualificationCertificate_upload");
            if (StringUtils.isNotEmpty(qualificationCertificateUpload)) {
                //必填
                if("1".equals(qualificationCertificateUpload)){
                    if(StringUtils.isEmpty(hyDriver.getQualificationImg())){
                        throw new JeecgBootException("请上传从业资格证!");
                    }
                }
            }
        }


        if(StringUtils.isBlank(hyDriver.getIssuingOrganizations())){
            throw new JeecgBootException("请填写驾驶证发证机关!");
        }

        hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());

        //获取自动审核时间段
        String driverExamineTime = settingService.getSettingValueByTag("driver_examine_time");
        if (StringUtils.isNotEmpty(driverExamineTime)) {
            String[] split = driverExamineTime.split("-");

            boolean inDate = isInDate(new Date(), split, "HH:mm:ss", "Asia/Shanghai");
            if (inDate) {
                hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
            } else {
                hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
            }
        } else {
            hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
        }


        //检查是否开启驾驶证验证
        String settingValue = settingService.getSettingValueByTag("driving_license_check");
        if ("1".equals(settingValue)) {
            String res = hyDriverService.checkDriver(hyDriver.getDrivingLicense(), hyDriver.getDriverName());
            if (StringUtils.isEmpty(res)) {
                hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
                return;
            }
            JSONObject res_obj = JSONObject.parseObject(res);
            String errorCode = res_obj.getString("error_code");
            if (StringUtils.isEmpty(errorCode)) {
                hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
                return;
            }

            if (!"0".equals(errorCode)) {
                LOGGER.info("HyDriverServiceImpl  doCheckDriver res_obj:{}", res);
                hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_TOREVIEWED.getCode());
                return;
            }
            String reason = res_obj.getString("reason");
            String result = res_obj.getString("result");
            if (StringUtils.isEmpty(result)) {
                throw new JeecgBootException(reason);
            }
            JSONObject results_obj = res_obj.getJSONObject("result");
            String status = results_obj.getString("status");
            if (reason.equals("一致") &&
                    (status.equals("正常") || status.equals("违法未处理") || status.equals("事故未处理"))) {
                hyDriver.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
            } else {
                throw new JeecgBootException(status);
            }
        }
    }

    /**
     * 比较两个时间 时分秒 大小
     *
     * @param s1
     * @param s2
     * @return
     */
    public static boolean compTime(String s1, String s2) {
        try {
            if (s1.indexOf(":") < 0 || s1.indexOf(":") < 0) {
                System.out.println("格式不正确");
            } else {
                String[] array1 = s1.split(":");
                int total1 = Integer.valueOf(array1[0]) * 3600 + Integer.valueOf(array1[1]) * 60 + Integer.valueOf(array1[2]);
                String[] array2 = s2.split(":");
                int total2 = Integer.valueOf(array2[0]) * 3600 + Integer.valueOf(array2[1]) * 60 + Integer.valueOf(array2[2]);
                return total1 - total2 > 0 ? true : false;
            }
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            return true;
        }
        return false;

    }

    public static void main(String[] args) {
        boolean b = compTime("10:00:00", "09:00:00");
        System.out.println(b);
    }


    @PutMapping(value = "/putDriverOpenId")
    public Result<?> putDriverOpenId(@RequestBody JSONObject jsonObject) {

        if(jsonObject.get("driverId")!=null && jsonObject.get("openid")!=null){
            String driverId = jsonObject.get("driverId").toString();
            String openid = jsonObject.get("openid").toString();
            if(StringUtils.isNotEmpty(driverId)&&StringUtils.isNotEmpty(openid)){
                HyDriver hyDriver = hyDriverService.getById(driverId);
                hyDriver.setWxOpenid(openid);
                hyDriverService.updateById(hyDriver);
                return Result.OK();
            }

        }

        return Result.OK();
    }
}
